/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package name_service;

import java.io.IOException;
import java.net.SocketAddress;
import java.util.logging.Level;
import java.util.logging.Logger;
import mware_lib.ObjectRef;
import mware_lib.tcp.Connection;
import name_service.GlobalNS;

/**
 *
 * @author zero.one
 */
public class ConnectionHandler implements Runnable {

    Connection clientSocket;
    GlobalNS ns;
    
    public ConnectionHandler(Connection clientSocket, GlobalNS ns)
    {
        this.clientSocket = clientSocket;
        this.ns = ns;
    }
    
    @Override
    public void run() {
        String message = "";
        try {
            message = (String) clientSocket.readObject();
        } catch (IOException ex) {
            Logger.getLogger(ConnectionHandler.class.getName()).log(Level.SEVERE, null, ex);
        }
        
        String[] strArr = message.split("/");

            if (strArr[0].equals("0")) {
                ObjectRef resolvedName = ns.resolve(message);
                if (resolvedName != null) {
                    try {
                        clientSocket.writeObject("1!" + resolvedName.stringRep());//noch andere stelle wo dieses trennzeichen relevant?
                    } catch (IOException ex) {
                        Logger.getLogger(GlobalNS.class.getName()).log(Level.SEVERE, null, ex);
                    }
                } else {
                    try {
                        clientSocket.writeObject("0");
                    } catch (IOException ex) {
                        Logger.getLogger(GlobalNS.class.getName()).log(Level.SEVERE, null, ex);
                    }
                }
            } else if (strArr[0].equals("1")) {
                try {
                    SocketAddress remoteEndpoint = clientSocket.getRemoteAddress();
                    ns.register(message, remoteEndpoint);
                    clientSocket.writeObject("");
                } catch (IOException ex) {
                    Logger.getLogger(GlobalNS.class.getName()).log(Level.SEVERE, null, ex);
                }
            } else {
                throw new IllegalArgumentException("Wrong Message Format");
            }
        }
    }
    

